package com.clss.commandhelper.function.videoroom;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.clss.commandhelper.base.BaseJson;
import com.clss.commandhelper.net.ApiConstants;
import com.clss.commandhelper.tools.Constant;
import com.clss.commandhelper.tools.Lg;
import com.clss.commandhelper.tools.SpHelper;
import com.clss.commandhelper.tools.eventbus.EventBusHelper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SecurityUploadService extends IntentService {
    private static final String TAG = "SecurityUploadService";

    public static final int UPLOAD_FINISH_CODE = 667;

    private static final String ACTION_FOO = "com.safe.peoplesafety.Function.security.action.FOO";
    private static final String ACTION_BAZ = "com.safe.peoplesafety.Function.security.action.BAZ";

    private static final String EXTRA_PARAM1 = "com.safe.peoplesafety.Function.security.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.safe.peoplesafety.Function.security.extra.PARAM2";
    private static final String EXTRA_PARAM3 = "com.safe.peoplesafety.Function.security.extra.PARAM3";
    private Gson mGson = new Gson();

    public SecurityUploadService() {
        super("SecurityUploadService");
    }

    public static void startActionFoo(Context context, String filePath, long fileTag, int fileType) {
        Intent intent = new Intent(context, SecurityUploadService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, filePath);
        intent.putExtra(EXTRA_PARAM2, fileTag);
        intent.putExtra(EXTRA_PARAM3, fileType);
        context.startService(intent);
    }

    /**
     * 线人上报线索
     * @param context
     * @param filePath
     * @param fileTag
     * @param fileType
     */
    public static void startActionBaz(Context context, String filePath, long fileTag, int fileType) {
        Intent intent = new Intent(context, SecurityUploadService.class);
        intent.setAction(ACTION_BAZ);
        intent.putExtra(EXTRA_PARAM1, filePath);
        intent.putExtra(EXTRA_PARAM2, fileTag);
        intent.putExtra(EXTRA_PARAM3, fileType);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final long param2 = intent.getLongExtra(EXTRA_PARAM2, 0);
                final int param3 = intent.getIntExtra(EXTRA_PARAM3, 0);
                handleActionFoo(param1, param2, param3);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final long param2 = intent.getLongExtra(EXTRA_PARAM2, 0);
                final int param3 = intent.getIntExtra(EXTRA_PARAM3, 0);
                handleActionBaz(param1, param2, param3);
            }
        }
    }

    private void handleActionFoo(String param1, long param2, int param3) {
        // TODO: Handle action Foo
//        throw new UnsupportedOperationException("Not yet implemented");
        if (TextUtils.isEmpty(param1)){
            return;
        }
        uploadFile(false, new File(param1), param2, param3);
    }

    private void handleActionBaz(String param1, long param2, int param3) {
        // TODO: Handle action Baz
//        throw new UnsupportedOperationException("Not yet implemented");
        if (TextUtils.isEmpty(param1)){
            return;
        }
        uploadFile(true, new File(param1), param2, param3);
    }

    private void uploadFile(boolean chooseType, File file, final long fileTag, final int fileType){
        if (file == null) {
            return;
        }
        Callback callback = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Lg.i(TAG, "---onFailure===" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                BaseJson baseJson = mGson.fromJson(res, BaseJson.class);
                if (baseJson.getCode() == 201) {
                    JsonElement jsonElement = (JsonElement) baseJson.getList().get(0);
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    String resourId = jsonObject.get("id").getAsString();
                    EventBusHelper.sendEventBusMsg(UPLOAD_FINISH_CODE, resourId, fileTag, fileType);
                    Lg.i(TAG, "---onResponse===" + resourId);
                }
            }
        };

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        MultipartBody body = builder
                .addFormDataPart("type", chooseType ? fileType + "" :"14")
                .addFormDataPart("files", file.getName(), RequestBody.create(null, file))
                .build();

        Request request = new Request.Builder()
                .url(ApiConstants.getUploadImageUrl())
                .post(body)
                .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                .build();

        new OkHttpClient
                .Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .build()
                .newCall(request)
                .enqueue(callback);
    }

}
